/**
 * 重排序再比较
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
export var isAnagram = function (s, t) {
  if (s.length !== t.length) return false
  return s.split('').sort().join('') === t.split('').sort().join('')
}

/**
 * 取出所有字每的个数比较
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
export var isAnagram2 = function (s, t) {
  if (s.length !== t.length) return false
  const countMap = new Map()
  for (let i = 0; i < s.length; i++) {
    const char = s[i]
    if (countMap.has(char)) {
      countMap.set(char, countMap.get(char) + 1)
    } else {
      countMap.set(char, 1)
    }
  }

  for (let i = 0; i < t.length; i++) {
    const char = t[i]
    if (countMap.has(char)) {
      countMap.set(char, countMap.get(char) - 1)
    } else {
      return false
    }
  }
  return Array.from(countMap.keys()).every(key => countMap.get(key) === 0)
}

/**
 * 取出所有字每的个数比较(好像比方法2快点)
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
export var isAnagram3 = function (s, t) {
  if (s.length !== t.length) return false
  const countMap = {}
  for (let i = 0; i < s.length; i++) {
    const char = s[i]
    countMap[char] = countMap[char] ? countMap[char] + 1 : 1
  }

  for (let i = 0; i < t.length; i++) {
    const char = t[i]
    if (typeof countMap[char] === 'undefined') return false
    countMap[char]--
  }
  return Object.keys(countMap).every(key => countMap[key] === 0)
}

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
export var isAnagram4 = function (s, t) {
  if (s.length != t.length) return false
  const res = new Array(26).fill(0)
  const base = 97
  for (let i = 0; i < s.length; i++) {
    res[s[i].charCodeAt() - base]++
  }
  for (let i = 0; i < t.length; i++) {
    res[t[i].charCodeAt() - base]--
  }
  return res.every(item => item === 0)
}
